package com.example.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.example.entity.User;
import com.example.mapper.RoleMapper;
import com.example.mapper.UserMapper;
import com.example.vo.LoginUser;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 朽
 */
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {


    private UserMapper userMapper;

    private RoleMapper roleMapper;


    @Override
    public UserDetails loadUserByUsername(String phone){
        User user = userMapper.existsByPhone(phone);
        if (ObjectUtil.isEmpty(user)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        if (user.getDeleteFlag() != null && user.getDeleteFlag().booleanValue() == true) {
            throw new UsernameNotFoundException("账户已注销");
        }
        if (user.getDisabled() != null && user.getDisabled().booleanValue() == true) {
            throw new UsernameNotFoundException("账户已禁用");
        }
        if (ObjectUtil.isEmpty(user.getPassword())) {
            throw new BadCredentialsException("密码无效");
        }
        //查询用户角色列表
        List<Long> roleIds = userMapper.getUserRoles(user.getId());
        List<String> permissions = new ArrayList<>();
        // 当角色列表不为空时，进行权限查询
        if(roleIds != null && !roleIds.isEmpty()){
            permissions = roleMapper.getPermissionsByRoleIds(roleIds);
        }
        return new LoginUser(user,permissions);
    }
}